import { assign } from 'lodash'
import { fetchTypes, fetchTrees, fetchEditTemplate, fetchDeleteTemplate, fetchTemplate } from '@/api/templateCustom'

const defaultState = () => {
  return {
    typeList: [],
    treeList: [],
    loadTempTable: false
  }
}

export default {
  namespaced: true,
  name: 'templateCustom',
  state: defaultState(),
  mutations: {
    REST_STATE(state) {
      state = assign(state, defaultState())
    },
    CHANGE_TYPE_LIST(state, list) {
      state.typeList = list
    },
    CHANGE_TREE_LIST(state, list) {
      state.treeList = list
    },
    CHANGE_LOAD_TEMP_TABLE(state, flag) {
      state.loadTempTable = flag
    }
  },
  actions: {
    clearStore(ctx) {
      ctx.commit('REST_STATE')
    },
    async getTypeList(ctx) {
      const { code, date } = await fetchTypes()
      if (code === 200) {
        ctx.commit('CHANGE_TYPE_LIST', date)
      } else {
        ctx.commit('CHANGE_TYPE_LIST', [])
      }
    },
    async getTreeList(ctx) {
      const { code, date } = await fetchTrees()
      if (code === 200) {
        ctx.commit('CHANGE_TREE_LIST', date)
      } else {
        ctx.commit('CHANGE_TREE_LIST', [])
      }
    },
    async addAndEditTemp(ctx, data) {
      const ret = await fetchEditTemplate(data)
      return ret
    },
    changeLoadTempTable(ctx, flag) {
      ctx.commit('CHANGE_LOAD_TEMP_TABLE', flag)
    },
    async loadDeleteTemp(ctx, data) {
      const ret = await fetchDeleteTemplate(data)
      return ret
    },
    async loadTempDetail(ctx, params) {
      const ret = await fetchTemplate(params)
      return ret
    }
  }
}
